from django.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver

from user.models import BBSUser


# Create your models here.
class CataLogModel(models.Model):
    name = models.CharField("栏目名称", max_length=100)
    moderator = models.ForeignKey(BBSUser, verbose_name="版主")
    priority = models.SmallIntegerField("优先级", default=0)

    class Meta:
        verbose_name = "栏目"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.name

    __str__ = __unicode__


class PostModel(models.Model):
    title = models.CharField("标题", max_length=200)
    catalog = models.ForeignKey(CataLogModel)
    content = models.TextField("内容")
    create_at = models.DateTimeField(auto_now_add=True, editable=False)
    reward = models.SmallIntegerField("悬赏", default=0, choices=[(i, i) for i in [0, 20, 40, 60, 80, 100]])
    creator = models.ForeignKey(BBSUser, verbose_name="作者")
    is_closed = models.BooleanField("已结帖", default=False)
    is_top = models.BooleanField("置顶", default=False)
    is_cream = models.BooleanField("精华", default=False)
    accepted = models.BooleanField("已采纳", default=False)
    viewed = models.ManyToManyField(BBSUser, related_name="viewed", blank=True, editable=False)
    like = models.ManyToManyField(BBSUser, related_name="like", blank=True)

    class Meta:
        verbose_name = "帖子"
        verbose_name_plural = verbose_name
        ordering = ('-create_at',)

    @property
    def view_count(self):
        return self.viewed.count()

    @property
    def comment_count(self):
        return self.commentmodel_set.count()

    @property
    def like_count(self):
        return self.like.count()

    def __unicode__(self):
        return self.title

    __str__ = __unicode__


@receiver(post_delete, sender=PostModel)
def payback_coin(instance, **kwargs):
    instance.creator.coin += instance.reward
    instance.creator.save()
